package cn.sylinx.horm.config;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import cn.sylinx.horm.proxy.ProxyObjectRegistry;
import cn.sylinx.horm.proxy.command.annotation.Command;
import cn.sylinx.horm.resource.io.ClassScanner;
import cn.sylinx.horm.util.GLog;
import cn.sylinx.horm.util.StrKit;

class CommandLoader {

    private final OrmConfig ormConfig;

    private final AtomicInteger count = new AtomicInteger(0);

    CommandLoader(OrmConfig ormConfig) {
        this.ormConfig = ormConfig;
    }

    private void loadOne(String pkg) {

        // Command 扫描包，如果为空，则全项目扫描
        if (StrKit.isBlank(pkg)) {
            // commandScanPackage
            GLog.warn("horm.config.command-scan-package没有配置，这将导致花费更多时间扫描整个项目");
        }
        GLog.info("扫描包:{}, 寻找@Command对象", StrKit.isBlank(pkg) ? "整个项目" : pkg);

        ClassScanner.scanAllPackageByAnnotation(pkg, Command.class).forEach(cmd -> {
            ProxyObjectRegistry.INSTANCE.register(cmd);
            count.incrementAndGet();
        });

    }

    public void load() {

        // Command 扫描包，如果为空，则全项目扫描
        String commandScanPackage = ormConfig.getCommandScanPackage();
        List<String> pkgs = new ArrayList<>();
        if (StrKit.isBlank(commandScanPackage)) {
            pkgs.add("");
        } else {
            String[] splitPkg = commandScanPackage.split(",");
            for (String s : splitPkg) {
                if (!StrKit.isBlank(s)) {
                    pkgs.add(s);
                }
            }
        }
        for (String pkg : pkgs) {
            loadOne(pkg);
        }
        GLog.info("寻找@Command对象完毕，总计:{}", count.get());

    }
}
